var express = require('express')
var router = express.Router()
const path = require('path')
const fs = require('fs')
const multer = require('multer')

// 目标目录：/uploads/pcproductimg
const uploadRoot = path.join(__dirname, '..', 'uploads', 'pcproductimg')
try {
  if (!fs.existsSync(uploadRoot)) fs.mkdirSync(uploadRoot, { recursive: true })
} catch (_) {}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadRoot)
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname) || '.jpg'
    const filename = `pc_${Date.now()}_${Math.floor(Math.random()*1e9)}${ext}`
    cb(null, filename)
  }
})

const upload = multer({ storage })

// 上传接口
router.post('/upload', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).send({ success: false, message: '未接收到文件' })
    }
    
    const relativeUrl = `/uploads/pcproductimg/${req.file.filename}`
    res.send({ success: true, data: { url: relativeUrl, filename: req.file.filename } })
  } catch (error) {
    res.status(500).send({ success: false, message: '上传失败', error: error.message })
  }
})

// =========== 标签同步与获取 ==========
const { productModel } = require('../db/models/cosmetic')
const { ProductCategoryModel } = require('../db/product_category')
const { ProductTypeModel } = require('../db/producttype')

// 手动触发同步：GET /pcproductimg/sync-tags
router.get('/sync-tags', async (req, res) => {
  try {
    const cursor = productModel.find({}, { tags: 1 }).cursor()
    const seen = new Set()
    let scanned = 0
    let inserted = 0

    for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
      scanned++
      if (!doc.tags || !Array.isArray(doc.tags)) continue
      for (const rawTag of doc.tags) {
        const tag = String(rawTag || '').trim()
        if (!tag || seen.has(tag)) continue
        seen.add(tag)
        const exists = await ProductCategoryModel.findOne({ name: tag })
        if (!exists) {
          await ProductCategoryModel.create({ name: tag })
          inserted++
        }
      }
    }
    res.send({ success: true, message: '标签同步完成', data: { scanned, inserted, totalUnique: seen.size } })
  } catch (error) {
    res.status(500).send({ success: false, message: '同步标签失败', error: error.message })
  }
})

// 获取全部标签：GET /pcproductimg/tags
router.get('/tags', async (req, res) => {
  try {
    const docs = await ProductCategoryModel.find({}, { name: 1 }).sort({ name: 1 })
    res.send({ success: true, data: docs.map(d => ({ id: d._id, name: d.name })) })
  } catch (error) {
    res.status(500).send({ success: false, message: '获取标签失败', error: error.message })
  }
})

// 新增标签：POST /pcproductimg/tags  body: { name }
router.post('/tags', async (req, res) => {
  try {
    let { name } = req.body || {}
    name = (name || '').trim()
    if (!name) {
      return res.status(400).send({ success: false, message: '标签名称不能为空' })
    }

    // 已存在直接返回
    let exist = await ProductCategoryModel.findOne({ name })
    if (exist) {
      return res.send({ success: true, data: { id: exist._id, name: exist.name }, message: '已存在' })
    }

    const created = await ProductCategoryModel.create({ name })
    res.status(201).send({ success: true, data: { id: created._id, name: created.name }, message: '创建成功' })
  } catch (error) {
    res.status(500).send({ success: false, message: '创建标签失败', error: error.message })
  }
})

// =========== 产品分类管理 ==========

// 获取产品分类列表：GET /pcproductimg/categories
router.get('/categories', async (req, res) => {
  try {
    const { page = 1, pageSize = 20, name } = req.query
    const query = {}
    
    // 名称模糊搜索
    if (name && name.trim()) {
      query.name = { $regex: name.trim(), $options: 'i' }
    }

    const skip = (parseInt(page) - 1) * parseInt(pageSize)
    const limit = parseInt(pageSize)

    const [categories, total] = await Promise.all([
      ProductTypeModel.find(query)
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(limit),
      ProductTypeModel.countDocuments(query)
    ])

    res.send({
      success: true,
      data: {
        list: categories,
        total,
        page: parseInt(page),
        pageSize: limit
      }
    })
  } catch (error) {
    res.status(500).send({ success: false, message: '获取分类列表失败', error: error.message })
  }
})

// 获取所有分类（用于下拉选择）：GET /pcproductimg/categories/all
router.get('/categories/all', async (req, res) => {
  try {
    const categories = await ProductTypeModel.find(
      {},
      { name: 1, _id: 1 }
    ).sort({ name: 1 })
    
    res.send({
      success: true,
      data: categories.map(cat => ({
        id: cat._id,
        name: cat.name
      }))
    })
  } catch (error) {
    res.status(500).send({ success: false, message: '获取分类选项失败', error: error.message })
  }
})

// 新增产品分类：POST /pcproductimg/categories  body: { name }
router.post('/categories', async (req, res) => {
  try {
    let { name } = req.body || {}
    name = (name || '').trim()
    
    if (!name) {
      return res.status(400).send({ success: false, message: '分类名称不能为空' })
    }

    // 检查是否已存在
    const exist = await ProductTypeModel.findOne({ name })
    if (exist) {
      return res.status(400).send({ success: false, message: '分类名称已存在' })
    }

    const categoryData = {
      name
    }

    const created = await ProductTypeModel.create(categoryData)
    res.status(201).send({
      success: true,
      data: created,
      message: '创建分类成功'
    })
  } catch (error) {
    res.status(500).send({ success: false, message: '创建分类失败', error: error.message })
  }
})

// 更新产品分类：PUT /pcproductimg/categories/:id
router.put('/categories/:id', async (req, res) => {
  try {
    const { id } = req.params
    let { name } = req.body || {}
    
    if (!id) {
      return res.status(400).send({ success: false, message: '分类ID不能为空' })
    }

    if (!name || !name.trim()) {
      return res.status(400).send({ success: false, message: '分类名称不能为空' })
    }

    const updateData = {
      name: name.trim()
    }
    
    // 检查名称是否与其他分类重复
    const exist = await ProductTypeModel.findOne({ name: updateData.name, _id: { $ne: id } })
    if (exist) {
      return res.status(400).send({ success: false, message: '分类名称已存在' })
    }

    const updated = await ProductTypeModel.findByIdAndUpdate(
      id,
      updateData,
      { new: true, runValidators: true }
    )

    if (!updated) {
      return res.status(404).send({ success: false, message: '分类不存在' })
    }

    res.send({
      success: true,
      data: updated,
      message: '更新分类成功'
    })
  } catch (error) {
    res.status(500).send({ success: false, message: '更新分类失败', error: error.message })
  }
})

// 删除产品分类：DELETE /pcproductimg/categories/:id
router.delete('/categories/:id', async (req, res) => {
  try {
    const { id } = req.params
    
    if (!id) {
      return res.status(400).send({ success: false, message: '分类ID不能为空' })
    }

    const deleted = await ProductTypeModel.findByIdAndDelete(id)
    
    if (!deleted) {
      return res.status(404).send({ success: false, message: '分类不存在' })
    }

    res.send({
      success: true,
      message: '删除分类成功'
    })
  } catch (error) {
    res.status(500).send({ success: false, message: '删除分类失败', error: error.message })
  }
})

// 批量删除产品分类：DELETE /pcproductimg/categories/batch
router.delete('/categories/batch', async (req, res) => {
  try {
    const { ids } = req.body || {}
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).send({ success: false, message: '请提供要删除的分类ID数组' })
    }

    const result = await ProductTypeModel.deleteMany({ _id: { $in: ids } })

    res.send({
      success: true,
      message: `成功删除 ${result.deletedCount} 个分类`,
      deletedCount: result.deletedCount
    })
  } catch (error) {
    res.status(500).send({ success: false, message: '批量删除分类失败', error: error.message })
  }
})

module.exports = router
